package joe;

public class MemBuf {
	private final long ptr;

	public MemBuf(long size, long align) {
		var basePtr = UnsafeUtil.allocateMemory(size + align - 1);
		Cleaner.addGlobal(this, () -> UnsafeUtil.freeMemory(basePtr));
		ptr = MemPool.align(basePtr, align);
	}

	public long ptr() {
		return ptr;
	}

	public long ptr(long offset) {
		return ptr + offset;
	}

	public int getInt() {
		return UnsafeUtil.getInt(ptr);
	}

	public int getInt(int index) {
		return UnsafeUtil.getInt(ptr + index * 4L);
	}

	public void setInt(int v) {
		UnsafeUtil.putInt(ptr, v);
	}

	public void setInt(int index, int v) {
		UnsafeUtil.putInt(ptr + index * 4L, v);
	}

	public long getLong() {
		return UnsafeUtil.getLong(ptr);
	}

	public long getLong(int index) {
		return UnsafeUtil.getLong(ptr + index * 8L);
	}

	public void setLong(long v) {
		UnsafeUtil.putLong(ptr, v);
	}

	public void setLong(int index, long v) {
		UnsafeUtil.putLong(ptr + index * 8L, v);
	}

	public float getFloat() {
		return UnsafeUtil.getFloat(ptr);
	}

	public float getFloat(int index) {
		return UnsafeUtil.getFloat(ptr + index * 4L);
	}

	public void setFloat(float v) {
		UnsafeUtil.putFloat(ptr, v);
	}

	public void setFloat(int index, float v) {
		UnsafeUtil.putFloat(ptr + index * 4L, v);
	}
}
